package com.have.blog.picture.service.impl;

import com.google.gson.Gson;
import com.have.blog.picture.service.QiniuService;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class QiniuServiceImpl implements QiniuService {
    @Autowired
    private UploadManager uploadManager;

    @Autowired
    private Auth auth;

    @Value("${qiniu.bucket}")
    private String bucket;

    private StringMap putPolicy;

    @Override
    public String uploadFile(MultipartFile filedata, String filename) {
        try {
            byte[] file = filedata.getBytes();
            String uploadToken = getUploadToken();
            Response response = this.uploadManager.put(file, filename, uploadToken);
            //解析上传的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(),DefaultPutRet.class);
            String imageName = putRet.hash;
            int retry = 0;
            while(response.needRetry() && retry < 3){
                response = this.uploadManager.put(file, filename, getUploadToken());

            }
            return "/" + filename;
        } catch (IOException e) {
            log.error("upload failed:", e.getMessage(), e);
            return null;
        }
    }

    private String getUploadToken(){
        return this.auth.uploadToken(bucket,null,3600,putPolicy);
    }

}
